package com.tandashi.springbootstudy01.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.tandashi.springbootstudy01.entity.user.LoginUser;
import com.tandashi.springbootstudy01.entity.user.User;
import com.tandashi.springbootstudy01.service.StrategyFactory;
import org.apache.commons.lang3.time.DateUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {

    private static final long TTL = DateUtils.MILLIS_PER_DAY;

    private static final String TOKEN_SECRET = "Study@2024";

    public static String encode(LoginUser user){
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);

        Map<String,Object> header = new HashMap<>(2);
        header.put("Type","Jwt");
        header.put("alg","HS256");

        Date expire = new Date(System.currentTimeMillis() + TTL);

        return JWT.create()
                .withHeader(header)
                .withClaim("unionId",user.getUnionid()).withClaim("openId",user.getOpenid()).withClaim("customerId",user.getCustomerId())
                .withExpiresAt(expire).sign(algorithm);
    }


    public static LoginUser decode(String token){
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        JWTVerifier verifier = JWT.require(algorithm).build();
        DecodedJWT jwt = verifier.verify(token);

        LoginUser loginUser = new LoginUser();
        loginUser.setUnionid(jwt.getClaim("unionId").asString());
        loginUser.setOpenid(jwt.getClaim("openId").asString());
        loginUser.setCustomerId(jwt.getClaim("customerId").asString());

        return loginUser;

    }


    public static String getToken(){
        Map<String, Object> header = new HashMap<>(2);
        header.put("typ","JWT");
        header.put("alg","HS256");

        Date expire = new Date(System.currentTimeMillis()+ 60 * 1000);
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);

        String token = JWT.create()
                .withHeader(header)
                .withClaim("userId", 21)
                .withClaim("userName", "baobao")
                .withExpiresAt(expire)
                .sign(algorithm);
        System.out.println("token:"+token);
        return token;
    }

    public static void resolveToken(String token){
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        JWTVerifier verifier = JWT.require(algorithm).build();
        DecodedJWT jwt = verifier.verify(token);
        Integer userId = jwt.getClaim("userId").asInt();
        System.out.println("userId:"+userId);
        String userName = jwt.getClaim("userName").asString();
        System.out.println("userName:"+userName);

    }
}
